/*
 *
 *  * Copyright 2015-2101 Shouqi Limousine & chauffeur Group.
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

package com.sq.plugin.redis.client;

import com.sq.plugin.redis.enums.SerializerEnum;
import com.sq.plugin.redis.facade.RedisSupport;
import com.sq.plugin.redis.serializer.Serializer;
import com.sq.plugin.redis.serializer.exception.SerializationException;
import com.sq.plugin.redis.serializer.impl.jackson.Jackson2JsonSerializer;
import com.sq.plugin.redis.serializer.util.SerializationUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangliang
 * @date 2018/5/16
 */
public abstract class BaseRedisClient implements RedisSupport {

    static final SerializerEnum DEFAULT_SERIALIZER = SerializerEnum.JACKSON2JSON;

    Serializer<Object> serializer;

    void serializerInit(SerializerEnum se) {
        if (se == DEFAULT_SERIALIZER) {
            this.serializer = new Jackson2JsonSerializer();
        } else {
            throw new SerializationException("error serializer type.");
        }
    }

    public <T extends Collection<?>> T deserializeValues(Collection<byte[]> rawValues, Class<T> type) {
        if (rawValues == null) {
            return null;
        } else {
            Object values = List.class.isAssignableFrom(type) ? new ArrayList(rawValues.size()) : new LinkedHashSet(rawValues.size());
            Iterator iterator = rawValues.iterator();

            while (iterator.hasNext()) {
                byte[] bs = (byte[]) iterator.next();
                ((Collection) values).add(serializer.deserialize(bs, Object.class));
            }

            return (T) values;
        }
    }



    public Map<byte[], byte[]> serializerMap(Map<String, Object> map) {
        if (map == null) {
            return SerializationUtils.EMPTY_MAP;
        }

        Map<byte[], byte[]> res = new ConcurrentHashMap<>(map.size());
        try {
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> e : entries) {
                res.put(getKey(e.getKey()), serializer.serialize(e.getValue()));
            }
        } catch (Exception e) {
            throw new SerializationException("Could not encode map: " + e.getMessage(), e);
        }
        return res;
    }

    /**
     * 获取key的byte数组值
     * @param key
     * @return
     */
    protected abstract byte[] getKey(String key);

}
